<?php /** @noinspection ALL */

namespace app\controller;

use app\BaseController;
use app\Request;
use app\Result;
use thans\jwt\facade\JWTAuth;
use think\db\exception\DbException;
use think\facade\Db;
use think\db\exception\ModelNotFoundException;
use think\db\exception\DataNotFoundException;
use think\response\Json;

class User extends BaseController
{
    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws Exception
     */
    public function login(Request $request):Json
    {

        $username = $request->post("username");
        $privateKey = openssl_pkey_get_private(file_get_contents("./key/rsa_private_key.pem"));
        openssl_private_decrypt(base64_decode($request->post("password")), $password, $privateKey);
        $user = Db::table("user")->where("username", $username)->where("password", $password)->find();
        $token = JWTAuth::builder(["uuid" => $user["user_id"]]);
        return $user ? Result::success(array(
            "username" => $user['username'],
            "token" => $token,
        )) : Result::error(10001, "用户名或密码错误");
    }

    public function logout(Request $request)
    {
        $uerId = $request->param("userId");
        JWTAuth::refresh();
        return Result::success($uerId);
    }
}